#include "BackGroundLayer.h"
#include "GamePlayLayer.h"
#include "Global.h"
#include "Coin.h"
#include "Rock.h"

USING_NS_CC;

bool BackGroundLayer::init()
{
	if(!Layer::init())
	{
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();

	auto centerPos = visibleSize / 2;

	//auto spritebg = Sprite::create("PlayBG.png");
	//spritebg->setPosition(centerPos);
	//this->addChild(spritebg);

	map00 = TMXTiledMap::create("map00.tmx");

	this->addChild(map00);

	auto contentSize = map00->getContentSize();
	mapWidth = contentSize.width;

	map01 = TMXTiledMap::create("map01.tmx");
	map01->setPosition(mapWidth, 0);
	
	this->addChild(map01);

	auto spriteFrameCache = SpriteFrameCache::getInstance();

	spriteFrameCache->addSpriteFramesWithFile("background.plist");

	loadObjects(map00, 0);

	loadObjects(map01, 1);


	return true;
}

bool BackGroundLayer::checkAndReload(float eyeX)
{
	auto newMapIndex = (int)eyeX/mapWidth;

	if(mapIndex == newMapIndex)
	{
		return false;
	}
	if(newMapIndex % 2 == 0)
	{
		map01->setPositionX(mapWidth*(newMapIndex + 1));
		
	}
	else
	{
		map00->setPositionX(mapWidth*(newMapIndex + 1));
		loadObjects(map00, newMapIndex+1);
	}

	removeObjects(newMapIndex -1);

	mapIndex = newMapIndex;

	return true;
}

void BackGroundLayer::update(float dt)
{
	auto parent = getParent();

	auto gamePlayLayer = (GamePlayLayer*)parent->getChildByTag(TagOfLayer::GAMEPLAY_LAYER);

	float eyeX = gamePlayLayer->getEyeX();

	checkAndReload(eyeX);
}

void BackGroundLayer::loadObjects( cocos2d::TMXTiledMap* map, int _mapIndex )
{
	auto coinGroup = map->getObjectGroup("coin");
	auto coinArray = coinGroup->getObjects();
	
	for(int i = 0; i < coinArray.size(); i++)
	{
		Value object = coinArray.at(i);
		ValueMap objectInfo = object.asValueMap();

		auto coin = Coin::create(this, Vec2(objectInfo.at("x").asFloat() + mapWidth * _mapIndex, objectInfo.at("y").asFloat()));

		coin->set_map_index(_mapIndex);

		objects.pushBack(coin);

	}

	auto rockGroup = map->getObjectGroup("rock");
	auto rockArray = rockGroup->getObjects();

	for(int i = 0; i < rockArray.size(); i++)
	{
		Value object = rockArray.at(i);
		ValueMap objectInfo = object.asValueMap();

		auto rock = Rock::create(this, objectInfo.at("x").asFloat() + mapWidth * _mapIndex);

		rock->set_map_index(_mapIndex);
		objects.pushBack(rock);
	}

}


void BackGroundLayer::removeObjects(int _mapIndex)
{
	for(int i = 0; i < objects.size(); i++)
	{
		auto obj = objects.at(i);

		if(obj->getTag() == TagOfSprite::COIN_SPRITE)
		{
			Coin* coin = (Coin*)obj;
			if(coin->get_map_index() == _mapIndex)
			{
				coin->removeFromParent();
			}

		}
		else if(obj->getTag() == TagOfSprite::ROCK_SPRITE)
		{
			Rock* rock = (Rock*)obj;
			if(rock->get_map_index() == _mapIndex)
			{
				rock->removeFromParent();
			}
		}
	}
}